from django.http import JsonResponse
from rest_framework.views import APIView
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from .models import DictBiz
from .validate import EditValidate, AddValidate
from utils.utils import validateError, MyPaginator, filterFields, serializerJSON, responseSuccess, responseError
from .serializers import ParentListSerializer, ChildListSerializer, TreeSerializer, DetailSerializer

# 系统管理-字典管理-顶级字典
class ParentListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        filterDict = filterFields(DictBiz, queryDict)
        objs = DictBiz.objects.filter(parentId=None, **filterDict)
        paginator = MyPaginator(objs, **queryDict)
        serializers = ParentListSerializer(paginator.object_list, many=True, context={'exclude': ['children']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(paginator.data(datas)), safe=False)

# 系统管理-字典管理-获取指定字典的子集字典
class ChildListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        parentId = queryDict.get('parentId')
        if not parentId:
            return JsonResponse(responseError('parentId不能为空'), safe=False)
        filterDict = filterFields(DictBiz, queryDict)
        filterDict['parentId_id'] = filterDict.pop('parentId')
        objs = DictBiz.objects.filter(**filterDict)
        paginator = MyPaginator(objs, **queryDict)
        serializers = ChildListSerializer(paginator.object_list, many=True, context={'exclude': ['hasChildren']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(paginator.data(datas)), safe=False)

# 系统管理-字典管理-字典树结构
class TreeAPI(APIView):
    def get(self,req):
        objs = DictBiz.objects.filter(parentId=None)
        serializers = TreeSerializer(objs, many=True)
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)
    
# 系统管理-字典管理-详情
class DetailAPI(APIView):
    def get(self, req):
        id = req.query_params.dict().get("id")
        if not id:
            return JsonResponse(responseError('id不能为空'), safe=False)
        serializer = DetailSerializer(DictBiz.objects.get(pk=id), context={'exclude': ['children']})
        return JsonResponse(responseSuccess(serializer.data), safe=False)

# 系统管理-字典管理-根据条件查询字典
class DictionaryAPI(APIView):
    def get(self, req):
        queryDict = req.query_params.dict()
        filterDict = filterFields(DictBiz, queryDict)
        if filterDict.get('parentId'):
            filterDict['parentId_id'] = filterDict.pop('parentId')
        objs = DictBiz.objects.filter(dictValue__isnull=False, **filterDict)
        serializers = ChildListSerializer(objs, many=True, context={'exclude': ['children']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 新增/修改
class SubmitAPI(APIView):
    def post(self,req):
        data = req.data
        edit_id = data.get('id')
        if edit_id:
            try:
                obj = DictBiz.objects.get(id=int(edit_id))
            except MultipleObjectsReturned:
                return JsonResponse(responseError('存在多条数据'), safe=False)
            except ObjectDoesNotExist:
                return JsonResponse(responseError('编辑对象不存在'), safe=False)
            form = EditValidate(obj, data=data)
        else:
            form = AddValidate(data=data)
        if form.is_valid():
            if edit_id:
                obj = form.update(obj, form.validated_data)
            else:
                obj = form.create(form.validated_data)
            return JsonResponse(responseSuccess(str(obj.pk)), safe=False)
        # 格式化错误信息
        arr = validateError(form.errors)
        return JsonResponse(responseError(arr), safe=False)

# 删除
class RemoveAPI(APIView):
    def post(self,req):
        ids = req.query_params.dict().get('ids')
        if not ids:
            return JsonResponse(responseError('缺少参数'), safe=False)
        ids = ids.split(',')
        if not DictBiz.objects.filter(id__in=ids).exists():
            return JsonResponse(responseError('删除对象不存在'), safe=False)
        result = DictBiz.objects.filter(id__in=ids).delete()
        if result:
            return JsonResponse(responseSuccess(), safe=False)
        return JsonResponse(responseError('删除失败'), safe=False)
    
